﻿namespace EyeOpen.Messaging
{
	using System;
	using System.Collections.Generic;

	public static class MessageBroker
	{
		private static MessageBrokerImplementation messageBroker;

		private static MessageBrokerImplementation MessageBrokerImpl
		{
			get
			{
				if (messageBroker == null)
				{
					messageBroker = new MessageBrokerImplementation();
				}

				return messageBroker;
			}
		}
		
		public static void Send<T>(T message)
		{
			MessageBrokerImpl.Send(message);
		}

		public static void Register<T>(Action<T> func)
		{
			MessageBrokerImpl.Register(func);
		}


		private class MessageBrokerImplementation
		{
			private readonly IDictionary<Type, object> messageDictionary =
				new Dictionary<Type, object>();

			public void Send<T>(T message)
			{
				var action = messageDictionary[typeof(T)];

				((Action<T>)action).Invoke(message);
			}

			public void Register<T>(Action<T> func)
			{
				messageDictionary.Add(typeof(T), func);
			}
		}
	}
}